package com.eastfair.home.service.impl;

import cn.hutool.core.bean.BeanUtil;
//import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.eastfair.annotation.annotation.cache.Cache;
import com.eastfair.annotation.annotation.cache.Magic;
import com.eastfair.boot.request.PageParams;
import com.eastfair.boot.service.SuperServiceImpl;
import com.eastfair.builder.ExhibitorFeign;
import com.eastfair.builder.ReportBuilderFeign;
import com.eastfair.builder.dto.ExhibitorDTO;
import com.eastfair.builder.enumeration.ExhibitorProcessEnum;
import com.eastfair.builder.enumeration.ExhibitorSiteTypeEnum;
import com.eastfair.builder.vo.ExhibitorVO;
import com.eastfair.builder.vo.ReportBuilderVO;
import com.eastfair.constant.BusinessConstant;
import com.eastfair.core.base.R;
import com.eastfair.core.context.ContextUtil;
import com.eastfair.core.exception.BizException;
import com.eastfair.core.exception.NoBackBizException;
import com.eastfair.core.utils.ConvertUtil;
import com.eastfair.home.dao.BoothAcceptanceRecordMapper;
import com.eastfair.home.dto.BoothAcceptanceDetailDTO;
import com.eastfair.home.dto.BoothAcceptanceRecordDTO;
import com.eastfair.home.dto.BoothAcceptanceRecordQuery;
import com.eastfair.home.entity.BoothAcceptanceDetail;
import com.eastfair.home.entity.BoothAcceptanceRecord;
import com.eastfair.home.entity.SupervisionItemManagement;
import com.eastfair.home.enumeration.BoothAcceptanceRecordAcceptanceStatusEnum;
import com.eastfair.home.enumeration.BoothAcceptanceRecordAcceptanceTypeEnum;
import com.eastfair.home.exceptioncode.HomeExceptionCode;
import com.eastfair.home.service.BoothAcceptanceDetailService;
import com.eastfair.home.service.BoothAcceptanceRecordService;
import com.eastfair.home.service.HomeServiceProviderSpaceService;
import com.eastfair.home.service.SupervisionItemManagementService;
import com.eastfair.home.vo.BoothAcceptanceDetailVO;
import com.eastfair.home.vo.BoothAcceptanceRecordVO;
import com.eastfair.messagecenter.api.MsgServiceFeign;
import com.eastfair.messagecenter.util.SmsSendDtoUtil;
import com.eastfair.venuebooking.api.*;
import com.eastfair.venuebooking.vo.SpaceVO;
import com.eastfair.venueservice.consts.CommonConstants;
import com.eastfair.venueservice.dto.ExhibitionManageQuery;
import com.eastfair.venueservice.dto.ServiceProviderSpaceDTO;
import com.eastfair.venueservice.dto.ServiceProviderSpaceQuery;
import com.eastfair.venueservice.dto.SpaceAcceptanceQuery;
import com.eastfair.venueservice.enumeration.SpaceAcceptanceFinishStatusEnum;
import com.eastfair.venueservice.vo.ExhibitionManageVO;
import com.eastfair.venueservice.vo.ServiceProviderSpaceVO;
import com.eastfair.venueservice.vo.ServiceProviderVO;
import com.eastfair.venueservice.vo.SpaceAcceptanceVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * <p>
 * 业务实现类
 * 展台验收记录
 * </p>
 *
 * @author linan
 * @date 2022-11-29
 */
@Slf4j
@Service
//@DS("#thread.tenant")
public class BoothAcceptanceRecordServiceImpl extends SuperServiceImpl<BoothAcceptanceRecordMapper, BoothAcceptanceRecord> implements BoothAcceptanceRecordService {

    @Resource
    private HomeServiceProviderSpaceService homeServiceProviderSpaceService;
    @Resource
    private BoothAcceptanceDetailService boothAcceptanceDetailService;
    @Resource
    private ServiceProviderSpaceFeign serviceProviderSpaceFeign;
    @Resource
    private ExhibitorFeign exhibitorFeign;
    @Resource
    private ReportBuilderFeign reportBuilderFeign;
    @Resource
    private SpaceAcceptanceFeign spaceAcceptanceFeign;
    @Resource
    private ExhibitionManageFeign exhibitionManageFeign;
    @Resource
    private ServiceProviderFeign serviceProviderFeign;
    @Resource
    private MsgServiceFeign msgServiceFeign;

    /**
     * 处理逻辑删除相关处理
     *
     * @param modelList 实体
     * @return 是否成功
     */
    @Override
    protected R<Boolean> handlerRemoveByIdsOfLogic(Collection<BoothAcceptanceRecord> modelList) {
        modelList.stream().forEach(s -> {
            s.setIsDeleted(BusinessConstant.YES);
        });
        // TODO: 2021/10/29 这里需要操作其他业务，如清空角色等
        return R.successDef();
    }


    @Override
    protected R<Boolean> handlerSave(BoothAcceptanceRecord model) {
        model.setProjectId(ContextUtil.getProjectId());
        model.setSubsystemId(ContextUtil.getSubSystemId());
        return R.successDef();
    }
    /**
     * 通用查询
     *
     * @param modelDTO DTO
     * @param ids      主键id集合
     * @return list
     */
    @Override
    public List<BoothAcceptanceRecord> list(BoothAcceptanceRecordDTO modelDTO, List<Long> ids) {
        return ((BoothAcceptanceRecordService) AopContext.currentProxy()).listOfCache(modelDTO, ids);
    }


    /**
     * 缓存查询
     *
     * @param modelDTO DTO
     * @param ids      主键id集合
     * @return list
     */
    @Override
    @Cache(key = "",
            magic = @Magic(
                    key = "{" +
                            "{'isEnabled', #args[0]?.isEnabled}," +
                            "{'acceptanceType', #args[0]?.acceptanceType}," +
                            "{'exhibitionManageId', #args[0]?.exhibitionManageId}," +
                            "{'homeCourtId', #args[0]?.homeCourtId}," +
                            "{'exhibitorId', #args[0]?.exhibitorId}," +
                            "{'exhibitorName', #args[0]?.exhibitorName}," +
                            "{'builderId', #args[0]?.builderId}," +
                            "{'builderName', #args[0]?.builderName}," +
                            "{'spaceCode', #args[0]?.spaceCode}," +
                            "{'spaceName', #args[0]?.spaceName}," +
                            "{'siteCode', #args[0]?.siteCode}," +
                            "{'siteName', #args[0]?.siteName}," +
                            "{'acceptanceStatus', #args[0]?.acceptanceStatus}," +
                            "{'acceptanceBy', #args[0]?.acceptanceBy}," +
                            "{'acceptanceName', #args[0]?.acceptanceName}," +
                            "{'acceptanceMobile', #args[0]?.acceptanceMobile}," +
                            "{'acceptanceTime', #args[0]?.acceptanceTime}," +
                            "{'id', #args[1]}" +
                            "}"))
    public List<BoothAcceptanceRecord> listOfCache(BoothAcceptanceRecordDTO modelDTO, List<Long> ids) {
        //查询
        QueryWrapper<BoothAcceptanceRecord> queryWrapper = new QueryWrapper<>();
        if (modelDTO != null) {
            queryWrapper.lambda().eq(Objects.nonNull(modelDTO.getAcceptanceType()), BoothAcceptanceRecord::getAcceptanceType, modelDTO.getAcceptanceType());
            queryWrapper.lambda().eq(modelDTO.getExhibitionManageId() != null, BoothAcceptanceRecord::getExhibitionManageId, modelDTO.getExhibitionManageId());
            queryWrapper.lambda().eq(modelDTO.getHomeCourtId() != null, BoothAcceptanceRecord::getHomeCourtId, modelDTO.getHomeCourtId());
            queryWrapper.lambda().eq(modelDTO.getExhibitorId() != null, BoothAcceptanceRecord::getExhibitorId, modelDTO.getExhibitorId());
            queryWrapper.lambda().eq(StringUtils.isNotBlank(modelDTO.getExhibitorName()), BoothAcceptanceRecord::getExhibitorName, modelDTO.getExhibitorName());
            queryWrapper.lambda().eq(modelDTO.getBuilderId() != null, BoothAcceptanceRecord::getBuilderId, modelDTO.getBuilderId());
            queryWrapper.lambda().eq(StringUtils.isNotBlank(modelDTO.getBuilderName()), BoothAcceptanceRecord::getBuilderName, modelDTO.getBuilderName());
            queryWrapper.lambda().eq(StringUtils.isNotBlank(modelDTO.getSpaceCode()), BoothAcceptanceRecord::getSpaceCode, modelDTO.getSpaceCode());
            queryWrapper.lambda().eq(StringUtils.isNotBlank(modelDTO.getSpaceName()), BoothAcceptanceRecord::getSpaceName, modelDTO.getSpaceName());
            queryWrapper.lambda().eq(StringUtils.isNotBlank(modelDTO.getSiteCode()), BoothAcceptanceRecord::getSiteCode, modelDTO.getSiteCode());
            queryWrapper.lambda().eq(StringUtils.isNotBlank(modelDTO.getSiteName()), BoothAcceptanceRecord::getSiteName, modelDTO.getSiteName());
            queryWrapper.lambda().eq(Objects.nonNull(modelDTO.getAcceptanceStatus()), BoothAcceptanceRecord::getAcceptanceStatus, modelDTO.getAcceptanceStatus());
            queryWrapper.lambda().eq(modelDTO.getAcceptanceBy() != null, BoothAcceptanceRecord::getAcceptanceBy, modelDTO.getAcceptanceBy());
            queryWrapper.lambda().eq(StringUtils.isNotBlank(modelDTO.getAcceptanceName()), BoothAcceptanceRecord::getAcceptanceName, modelDTO.getAcceptanceName());
            queryWrapper.lambda().eq(StringUtils.isNotBlank(modelDTO.getAcceptanceMobile()), BoothAcceptanceRecord::getAcceptanceMobile, modelDTO.getAcceptanceMobile());
            queryWrapper.lambda().eq(modelDTO.getAcceptanceTime() != null, BoothAcceptanceRecord::getAcceptanceTime, modelDTO.getAcceptanceTime());
        }
        if (ids != null && !ids.isEmpty()) {
            queryWrapper.lambda().in(BoothAcceptanceRecord::getId, ids);
        }
        queryWrapper.lambda().eq(BoothAcceptanceRecord::getIsDeleted, BusinessConstant.DELETE_NO);
        List<BoothAcceptanceRecord> modelList = list(queryWrapper);
        return modelList;
    }

    @Override
    public List<BoothAcceptanceRecordVO> getBoothAcceptanceRecord(BoothAcceptanceRecordQuery query) {
        List<BoothAcceptanceRecord> list = list(new QueryWrapper<BoothAcceptanceRecord>().lambda()
                .eq(Objects.nonNull(query.getId()), BoothAcceptanceRecord::getId, query.getId())
                .eq(BoothAcceptanceRecord::getIsDeleted, BusinessConstant.NO)
                .eq(BoothAcceptanceRecord::getIsEnabled, BusinessConstant.YES)
                .eq(StringUtils.isNotBlank(query.getAcceptanceType()), BoothAcceptanceRecord::getAcceptanceType, query.getAcceptanceType())
                .eq(StringUtils.isNotBlank(query.getSiteCode()), BoothAcceptanceRecord::getSiteCode, query.getSiteCode())
                .eq(Objects.nonNull(query.getExhibitionManageId()), BoothAcceptanceRecord::getExhibitionManageId, query.getExhibitionManageId())
                .eq(Objects.nonNull(query.getHomeCourtId()), BoothAcceptanceRecord::getHomeCourtId, query.getHomeCourtId())
                .eq(Objects.nonNull(query.getBuilderId()), BoothAcceptanceRecord::getBuilderId, query.getBuilderId()));
        Map<String, BoothAcceptanceRecord> acceptanceRecordMap = list.stream().collect(Collectors.toMap(e -> e.getSpaceCode() + "-" + e.getSiteCode(), Function.identity()));
        PageParams<ExhibitorDTO> pageParams= new PageParams<>();
        pageParams.setSize(999999);
        pageParams.setCurrent(1);
        ExhibitorDTO serviceProviderSpaceQuery = new ExhibitorDTO();
        serviceProviderSpaceQuery.setSpaceCode(query.getSpaceCode());
        serviceProviderSpaceQuery.setExhibitionManageId(query.getExhibitionManageId());
        if(StringUtils.isNotBlank(query.getSiteType())){
            serviceProviderSpaceQuery.setSiteType(ExhibitorSiteTypeEnum.get(query.getSiteType()));
        }
        pageParams.setModel(serviceProviderSpaceQuery);
        // 从搭建商查询展位信息
        R<Page<ExhibitorVO>> pageR = homeServiceProviderSpaceService.queryServiceProviderSite(pageParams);
        List<BoothAcceptanceRecordVO> boothAcceptanceRecordVOS = new ArrayList<>();
        if(pageR.getIsSuccess()){
            List<ExhibitorVO> records = pageR.getData().getRecords();
            records = ConvertUtil.convertList(records,ExhibitorVO.class);
            for (ExhibitorVO record : records) {
                BoothAcceptanceRecordVO boothAcceptanceRecordVO = BeanUtil.copyProperties(record, BoothAcceptanceRecordVO.class,"id");
                boothAcceptanceRecordVO.setProcess(Objects.nonNull(record.getProcess())?record.getProcess().getCode():null);
                boothAcceptanceRecordVO.setExhibitorId(record.getId());
                BoothAcceptanceRecord boothAcceptanceRecord = acceptanceRecordMap.get(boothAcceptanceRecordVO.getSpaceCode() + "-" + boothAcceptanceRecordVO.getSiteCode());
                if(Objects.nonNull(boothAcceptanceRecord)){
                    // 验收状态
                    boothAcceptanceRecordVO.setAcceptanceStatus(boothAcceptanceRecord.getAcceptanceStatus());
                    // 验收人
                    boothAcceptanceRecordVO.setAcceptanceName(boothAcceptanceRecord.getAcceptanceName());
                    // 验收人手机号
                    boothAcceptanceRecordVO.setAcceptanceMobile(boothAcceptanceRecord.getAcceptanceMobile());
                    // 验收时间
                    boothAcceptanceRecordVO.setAcceptanceTime(boothAcceptanceRecord.getAcceptanceTime());
                    // id
                    boothAcceptanceRecordVO.setId(boothAcceptanceRecord.getId());
                }else {
                    boothAcceptanceRecordVO.setAcceptanceStatus(BoothAcceptanceRecordAcceptanceStatusEnum.UN_ACCEPTANCE);
                }
                // 查询展位报馆时的搭建商基本信息
                R<ReportBuilderVO> reportBuilderResult = reportBuilderFeign.getByExhibitorId(record.getId());
                if (reportBuilderResult.getIsSuccess()) {
                    ReportBuilderVO reportBuilderVO = reportBuilderResult.getData();
                    if (reportBuilderVO != null) {
                        // 封装搭建商施工负责人和电话
                        boothAcceptanceRecordVO.setConstructionPrincipal(reportBuilderVO.getConstructionPrincipal());
                    }
                }

                // 过滤搭建商
                if (Objects.isNull(query.getBuilderId()) || query.getBuilderId().equals(boothAcceptanceRecordVO.getBuilderId()) ) {
                    // 过滤关键词
                    if (StringUtils.isBlank(query.getKeyword()) || boothAcceptanceRecordVO.getSiteName().contains(query.getKeyword()) || boothAcceptanceRecordVO.getBuilderName().contains(query.getKeyword())) {
                        // 过滤验收状态
                        if (StringUtils.isBlank(query.getAcceptanceStatus()) || boothAcceptanceRecordVO.getAcceptanceStatus().getCode().equals(query.getAcceptanceStatus())) {
                            boothAcceptanceRecordVOS.add(boothAcceptanceRecordVO);
                        }
                    }
                }
            }
        }else {
            throw BizException.wrap(pageR.getCode(),pageR.getMsg());
        }
        return boothAcceptanceRecordVOS;
    }

    @Override
    @Transactional(rollbackFor=Exception.class)
    public BoothAcceptanceRecord saveAcceptance(BoothAcceptanceRecordDTO boothAcceptanceRecordDTO) {
        // 修改展位进度
        ExhibitorDTO exhibitorDTO = new ExhibitorDTO();
        exhibitorDTO.setId(boothAcceptanceRecordDTO.getExhibitorId());
        exhibitorDTO.setProcess(boothAcceptanceRecordDTO.getAcceptanceType().eq(BoothAcceptanceRecordAcceptanceTypeEnum.ARRANGEMENT)? ExhibitorProcessEnum.ARRANGEMENT:ExhibitorProcessEnum.DISMANTLING);
        exhibitorFeign.updateExhibitor(exhibitorDTO);
        BoothAcceptanceRecord boothAcceptanceRecord = BeanUtil.copyProperties(boothAcceptanceRecordDTO, BoothAcceptanceRecord.class);
        // 先删除历史记录
        removeHistory(boothAcceptanceRecordDTO);
        save(boothAcceptanceRecord);
        return boothAcceptanceRecord;
    }

    private void removeHistory(BoothAcceptanceRecordDTO boothAcceptanceRecordDTO) {
        update(new UpdateWrapper<BoothAcceptanceRecord>().lambda()
                .eq(BoothAcceptanceRecord::getIsDeleted,BusinessConstant.NO)
                .eq(BoothAcceptanceRecord::getExhibitionManageId, boothAcceptanceRecordDTO.getExhibitionManageId())
                .eq(BoothAcceptanceRecord::getHomeCourtId, boothAcceptanceRecordDTO.getHomeCourtId())
                .eq(BoothAcceptanceRecord::getBuilderId, boothAcceptanceRecordDTO.getBuilderId())
                .eq(BoothAcceptanceRecord::getSpaceName, boothAcceptanceRecordDTO.getSpaceName())
                .eq(BoothAcceptanceRecord::getSiteName, boothAcceptanceRecordDTO.getSiteName())
                .eq(BoothAcceptanceRecord::getAcceptanceType, boothAcceptanceRecordDTO.getAcceptanceType())
                .set(BoothAcceptanceRecord::getIsDeleted,BusinessConstant.YES));
    }

    @Override
    public BoothAcceptanceRecordVO getBoothAcceptanceDetail(BoothAcceptanceRecordQuery query) {
        List<BoothAcceptanceRecordVO> boothAcceptanceRecord = getBoothAcceptanceRecord(query);
        if(CollectionUtils.isNotEmpty(boothAcceptanceRecord)){
            if(Objects.nonNull(query.getId())){
                boothAcceptanceRecord = boothAcceptanceRecord.stream().filter(e -> Objects.nonNull(e.getId()) && e.getId().equals(query.getId())).collect(Collectors.toList());
                BoothAcceptanceRecordVO boothAcceptanceRecordVO= boothAcceptanceRecord.size() > 0 ? boothAcceptanceRecord.get(0) : null;
                if(Objects.nonNull(boothAcceptanceRecordVO)){
                    List<BoothAcceptanceDetailVO> detail = boothAcceptanceDetailService.getByAcceptanceRecordId(boothAcceptanceRecordVO.getId());
                    boothAcceptanceRecordVO.setBoothAcceptanceDetail(detail);
                }
                return boothAcceptanceRecordVO;
            }else {
                boothAcceptanceRecord = boothAcceptanceRecord.stream().filter(e ->  e.getSpaceCode().equals(query.getSpaceCode()) && e.getSiteCode().equals(query.getSiteCode()) ).collect(Collectors.toList());
                return boothAcceptanceRecord.size() > 0 ? boothAcceptanceRecord.get(0) : null;
            }
        }
        return boothAcceptanceRecord.get(0);
    }

    @Override
    @Transactional(rollbackFor=Exception.class)
    public Boolean saveBoothAcceptanceDetail(BoothAcceptanceRecordDTO dto) {
        Long id = dto.getId();
        // 校验是否可以发起验收
        check(dto);
        BoothAcceptanceRecord record;
        if (Objects.nonNull(id)) {
            record = getById(id);
        } else {
            List<BoothAcceptanceRecord> list = list(new QueryWrapper<BoothAcceptanceRecord>().lambda().eq(BoothAcceptanceRecord::getIsDeleted, BusinessConstant.NO)
                    .eq(BoothAcceptanceRecord::getIsEnabled, BusinessConstant.YES)
                    .eq(BoothAcceptanceRecord::getAcceptanceType, dto.getAcceptanceType())
                    .eq(BoothAcceptanceRecord::getSpaceCode, dto.getSpaceCode())
                    .eq(BoothAcceptanceRecord::getSiteCode, dto.getSiteCode()));
            if(CollectionUtils.isNotEmpty(list)){
                record=list.get(0);
            }else {
                record = saveAcceptance(dto);
            }
        }
        BoothAcceptanceRecord updateEntity = new BoothAcceptanceRecord();
        updateEntity.setId(record.getId());
        updateEntity.setAcceptanceStatus(dto.getAcceptanceStatus());
        updateEntity.setAcceptanceBy(dto.getAcceptanceBy());
        updateEntity.setAcceptanceName(dto.getAcceptanceName());
        updateEntity.setAcceptanceMobile(dto.getAcceptanceMobile());
        updateEntity.setAcceptanceTime(LocalDateTime.now());
        updateById(updateEntity);
        // 先作废历史记录
        boothAcceptanceDetailService.removeByRecordId(record.getId());
        List<BoothAcceptanceDetailDTO> boothAcceptanceDetailDTOS = dto.getBoothAcceptanceDetail();
        for (BoothAcceptanceDetailDTO boothAcceptanceDetailDTO : boothAcceptanceDetailDTOS) {
            boothAcceptanceDetailDTO.setAcceptanceRecordId(record.getId());
            BoothAcceptanceDetail boothAcceptanceDetail = BeanUtil.copyProperties(boothAcceptanceDetailDTO, BoothAcceptanceDetail.class);
            boothAcceptanceDetailService.save(boothAcceptanceDetail);
        }
        // 更新展位进度
        ExhibitorDTO exhibitorDTO = new ExhibitorDTO();
        exhibitorDTO.setId(record.getExhibitorId());
        if(dto.getAcceptanceStatus().eq(BoothAcceptanceRecordAcceptanceStatusEnum.PASS)){
            if (record.getAcceptanceType().eq(BoothAcceptanceRecordAcceptanceTypeEnum.ARRANGEMENT)) {
                exhibitorDTO.setProcess(ExhibitorProcessEnum.HAS_ARRANGEMENT);
            } else {
                exhibitorDTO.setProcess(ExhibitorProcessEnum.HAS_DISMANTLING);
            }
        }else if (dto.getAcceptanceStatus().eq(BoothAcceptanceRecordAcceptanceStatusEnum.NOT_PASS)){
            // 验收不通过，发短信
            sendMsg(record);
        }
        exhibitorFeign.updateExhibitor(exhibitorDTO);
        return true;
    }

    private void sendMsg(BoothAcceptanceRecord record) {
        Long builderId = record.getBuilderId();
        Long exhibitionManageId = record.getExhibitionManageId();
        // 查询展会名称和搭建商手机号
        ExhibitionManageQuery exhibitionManageQuery = new ExhibitionManageQuery();
        exhibitionManageQuery.setId(exhibitionManageId);
        R<ExhibitionManageVO> exhibitionManageVOR = exhibitionManageFeign.queryExhibitionManageDetail(exhibitionManageQuery);
        R<ServiceProviderVO> serviceProviderVOR = serviceProviderFeign.getById(builderId);
        String exhibitionManageName = null;
        String mobile = null;
        String spaceName = record.getSpaceName();
        String siteName = record.getSiteName();
        if (exhibitionManageVOR.getIsSuccess() && Objects.nonNull(exhibitionManageVOR.getData())
            && serviceProviderVOR.getIsSuccess() && Objects.nonNull(serviceProviderVOR.getData())) {
            ExhibitionManageVO data = exhibitionManageVOR.getData();
            exhibitionManageName =data.getExhibitionName();
            mobile =serviceProviderVOR.getData().getPrincipalMobile();
            if(Objects.nonNull(exhibitionManageName) && Objects.nonNull(mobile)){
                if (record.getAcceptanceType().eq(BoothAcceptanceRecordAcceptanceTypeEnum.ARRANGEMENT)) {
                    // 展台验收不通过
                    String content =String.format("%s您所负责搭建的%s-%s，未通过主场的展台验收，请访问搭建商业务系统查看具体原因。",exhibitionManageName,spaceName,siteName) ;
                    Set<String> nums =new HashSet<>(8);
                    nums.add(mobile);
                    msgServiceFeign.sendSmsMsg(SmsSendDtoUtil.sendSmsDto(CommonConstants.BUSINESS_COMMON, nums, content));
                } else {
                    // 撤展验收不通过
                    String content =String.format("%s您所负责搭建的%s-%s，未通过主场的撤展验收，请访问搭建商业务系统查看具体原因。",exhibitionManageName,spaceName,siteName) ;
                    Set<String> nums =new HashSet<>(8);
                    nums.add(mobile);
                    msgServiceFeign.sendSmsMsg(SmsSendDtoUtil.sendSmsDto(CommonConstants.BUSINESS_COMMON, nums, content));
                }
            }
        }
    }

    @Override
    public void removeByExhibitionManage(SupervisionItemManagement supervisionItemManagement,String acceptanceTypeEnum) {
        update(new UpdateWrapper<BoothAcceptanceRecord>().lambda()
                .eq(BoothAcceptanceRecord::getIsDeleted, BusinessConstant.NO)
                .eq(BoothAcceptanceRecord::getExhibitionManageId, supervisionItemManagement.getExhibitionManageId())
                .eq(BoothAcceptanceRecord::getHomeCourtId, supervisionItemManagement.getHomeCourtId())
                .eq(StringUtils.isNotBlank(acceptanceTypeEnum),BoothAcceptanceRecord::getAcceptanceType,acceptanceTypeEnum)
                .set(BoothAcceptanceRecord::getIsDeleted, BusinessConstant.YES));
    }

    /**
     * 校验是否可以发起验收
     * @param dto
     */
    private void check(BoothAcceptanceRecordDTO dto) {
        R<ExhibitorVO> exhibitor = exhibitorFeign.getExhibitor(dto.getExhibitorId());
        if(!exhibitor.getIsSuccess()){
            throw NoBackBizException.wrap(exhibitor.getCode(), exhibitor.getMsg());
        }
        ExhibitorProcessEnum process = exhibitor.getData().getProcess();
        if (dto.getAcceptanceType().eq(BoothAcceptanceRecordAcceptanceTypeEnum.ARRANGEMENT)) {
            if(Objects.isNull(process)){
                // 需要先交纳保证金
                throw NoBackBizException.wrap(HomeExceptionCode.NEED_IS_EARNEST_MONEY_SET);
            }
        } else if (dto.getAcceptanceType().eq(BoothAcceptanceRecordAcceptanceTypeEnum.DISMANTLING)) {
            if(Objects.isNull(process)){
                // 需要先交纳保证金
                throw NoBackBizException.wrap(HomeExceptionCode.NEED_IS_EARNEST_MONEY_SET);
            }
            if(process.eq(ExhibitorProcessEnum.IS_EARNEST_MONEY_SET) || process.eq(ExhibitorProcessEnum.ARRANGEMENT) ){
                // 需要先完成布展验收
                throw NoBackBizException.wrap(HomeExceptionCode.NEED_AFTER_ARRANGEMENT);
            }
        }
    }



    @Override
    public List<SpaceVO> getPassSpace(BoothAcceptanceRecordDTO dto) {
        // 查询主场展厅
        ServiceProviderSpaceQuery serviceProviderSpaceQuery = new ServiceProviderSpaceQuery();
        serviceProviderSpaceQuery.setExhibitionManageId(dto.getExhibitionManageId());
        serviceProviderSpaceQuery.setServiceProviderId(dto.getHomeCourtId());
        R<List<ServiceProviderSpaceVO>> serviceProviderSpace = serviceProviderSpaceFeign.queryServiceProviderSpace(serviceProviderSpaceQuery);
        Map<String, List<ServiceProviderSpaceVO>> serviceProviderSpaceMap = serviceProviderSpace.getData().stream().collect(Collectors.groupingBy(ServiceProviderSpaceVO::getSpaceCode));
        ExhibitorDTO exhibitorDTO = new ExhibitorDTO();
        exhibitorDTO.setExhibitionManageId(dto.getExhibitionManageId());
        // 查询是否已经在验收
        SpaceAcceptanceQuery spaceAcceptanceQuery = new SpaceAcceptanceQuery();
        spaceAcceptanceQuery.setCompanyId(dto.getHomeCourtId());
        spaceAcceptanceQuery.setExhibitionManageId(dto.getExhibitionManageId());
        PageParams<SpaceAcceptanceQuery> params = new PageParams<>();
        params.setModel(spaceAcceptanceQuery);
        params.setSize(999999);
        params.setCurrent(0);
        R<Page<SpaceAcceptanceVO>> iPageR = spaceAcceptanceFeign.querySpaceAcceptance(params);
        Map<String, List<SpaceAcceptanceVO>> spaceAcceptanceMap = ConvertUtil.convertList(iPageR.getData().getRecords(),SpaceAcceptanceVO.class).stream().collect(Collectors.groupingBy(SpaceAcceptanceVO::getSpaceCode));
        // 查询展会下所有展位
        R<List<ExhibitorVO>> listR = exhibitorFeign.queryExhibitors(exhibitorDTO);
        // 通过展厅分组
//        Map<String, List<ExhibitorVO>> allSpace = listR.getData().stream().filter(e->e.getSiteType().eq(ExhibitorSiteTypeEnum.SPECIAL)).collect(Collectors.groupingBy(ExhibitorVO::getSpaceCode));
        Map<String, List<ExhibitorVO>> allSpace = new HashMap<>();
                // 查询审核通过的展厅
        List<SpaceVO> passSpace = baseMapper.getPassSpace(dto);
        ArrayList<SpaceVO> spaceVOS = new ArrayList<>();
        listR.getData().stream().collect(Collectors.groupingBy(ExhibitorVO::getSpaceCode)).forEach((a,b)->{
            boolean flag = b.stream().allMatch(e -> e.getSiteType().eq(ExhibitorSiteTypeEnum.STANDARD));
            if(flag){
                ExhibitorVO exhibitorVO = b.get(0);
                SpaceVO spaceVO = BeanUtil.copyProperties(exhibitorVO, SpaceVO.class);
                spaceVOS.add(spaceVO);
            }else {
                List<ExhibitorVO> exhibitorVOS = new ArrayList<>();

                for (ExhibitorVO exhibitorVO : b) {
                    if(exhibitorVO.getSiteType().eq(ExhibitorSiteTypeEnum.SPECIAL)){
                        exhibitorVOS.add(exhibitorVO);
                        break;
                    }
                }
                if(CollectionUtils.isNotEmpty(exhibitorVOS)){
                    allSpace.put(a,exhibitorVOS);
                }
            }
        });
        for (SpaceVO spaceVO : passSpace) {
            List<ExhibitorVO> exhibitorVOS = allSpace.get(spaceVO.getSpaceCode());
            if (CollectionUtils.isNotEmpty(exhibitorVOS) && exhibitorVOS.size() == spaceVO.getSiteNum() && serviceProviderSpaceMap.containsKey(spaceVO.getSpaceCode())) {
                List<SpaceAcceptanceVO> spaceAcceptanceVOS = spaceAcceptanceMap.get(spaceVO.getSpaceCode());
                if(CollectionUtils.isEmpty(spaceAcceptanceVOS)){
                    spaceVOS.add(spaceVO);
                }else {
                    // 除了已取消，不存在其他类型记录，则添加
                    if(CollectionUtils.isEmpty(spaceAcceptanceVOS.stream().filter(e->!e.getFinishStatus().eq(SpaceAcceptanceFinishStatusEnum.CANCEL)).collect(Collectors.toList()))){
                        spaceVOS.add(spaceVO);
                    }
                }
            }
        }
        return spaceVOS;
    }

    public static void main(String[] args) {
        List<ExhibitorVO> list =new ArrayList<>();
        ExhibitorVO exhibitorVO = new ExhibitorVO();
        exhibitorVO.setSpaceCode("1");
        exhibitorVO.setSiteCode("1site");
        exhibitorVO.setSiteType(ExhibitorSiteTypeEnum.SPECIAL);
        ExhibitorVO exhibitorVO2 = new ExhibitorVO();
        exhibitorVO2.setSpaceCode("2");
        exhibitorVO2.setSiteCode("2site");
        exhibitorVO2.setSiteType(ExhibitorSiteTypeEnum.STANDARD);
        list.add(exhibitorVO);
        list.add(exhibitorVO2);
        Map<String, List<ExhibitorVO>> collect = list.stream().filter(e -> e.getSiteType().eq(ExhibitorSiteTypeEnum.SPECIAL)).collect(Collectors.groupingBy(ExhibitorVO::getSpaceCode));
        System.out.println(collect);
    }


    /**
     * do转vo
     *
     * @param model model
     * @return modelVo
     */
    @Override
    public BoothAcceptanceRecordVO doToVo(BoothAcceptanceRecord model) {
        BoothAcceptanceRecordVO modelVo = new BoothAcceptanceRecordVO();
        BeanUtils.copyProperties(model, modelVo);
        modelVo.setId(model.getId());
        return modelVo;
    }

    /**
     * do转vo
     *
     * @param modelList modelList
     * @return list
     */
    @Override
    public List<BoothAcceptanceRecordVO> doToVos(List<BoothAcceptanceRecord> modelList) {
        if (modelList == null || modelList.isEmpty()) {
            return null;
        }
        List<BoothAcceptanceRecordVO> result = new ArrayList<>();
        for (BoothAcceptanceRecord model : modelList) {
            result.add(doToVo(model));
        }
        return result;
    }
}
